<!-- 首页view -->
<!-- 路由:/ -->
<!-- 描述：搜索框，搜索引擎选择器，搜索框，搜索结果列表 -->
<template>
  <!-- logo显示 -->
  <div id="logo"><a title="PandaSO,一款简洁的搜索导航">
      <img alt="PandSo" src="../assets/img/pandaSO.svg" /><img src="../assets/img/simple-so.svg" /></a>
  </div>
  <!-- 搜索引擎，搜索框，搜索结果列表 -->
  <div v-if="engines" id="site-main">
    <div id="search-bar">
      <div id="container">
        <div id="headline-content">
          <div id="search-tab">
            <div v-for="engine_name in engine_names">
              <span v-bind:key="engine_name" v-if="engine_siwtch.switchList[engine_name]"
                :class="{ active: get_search_engine() === engine_name }" @click="set_search_engine(engine_name)">
                {{ engines[engine_name][3] }} </span>
            </div>
          </div>
          <!-- 创建了一个搜索功能的表单，表单提交后会跳转到指定的搜索引擎页面。 -->
          <form id="search-form" :action=engines[search_engine][0] target="_blank">
            <input id="search-keyword" ref="search_input" v-model="keyword" :name=engines[search_engine][1]
              :placeholder=engines[search_engine][2] autocomplete=off autofocus class="float-left" type="search"
              @focus="focus()" @blur="blur()" @keydown.down="down()" @keydown.prevent.up="up()"
              @keydown.enter="saveSearch()">
            <input id="search-form-submit" class="float-right" type="submit" value="搜索">
          </form>
          <!-- 搜索历史 -->
          <div id="search-history" v-show="showSearchHistory">
            <el-button type="danger" :icon="Delete" circle @click="clearHistory"></el-button>
            <ul style="list-style-type: none;">
              <li v-for="(searchRecord, index) in searchRecords" :key="index" @click="go_history(searchRecord)">{{ searchRecord }}</li>
            </ul>
          </div>
          <div id="search-hot" :style="search_hot_display">
            <ul>
              <li v-for="(key, index) in keywords" v-bind:key="key" :class="{ selected: key_selected === index }"
                @click="go_submit(key)">
                <span :class="'search_index' + index">{{ index + 1 }}</span>{{ key }}
              </li>
            </ul>
          </div>
        </div>
      </div>
    </div>
  </div>
  <!-- 历史今日 -->
  <HistoryToday class="history-today"></HistoryToday>

  <!-- Tag书签 -->
  <Tag></Tag>
  <!-- Setting组件 -->
  <!-- 设置图标 -->
  <div id="setting-icon" @click="showSettingsPanel = !showSettingsPanel">
    <img alt="PandSo" src="../assets/img/setting.svg" />
  </div>
  <div id="setting-open" v-show="showSettingsPanel">
    <Setting />
  </div>
  <!-- 覆盖Setting以外的组件 -->
  <div class="overlay" v-show="showSettingsPanel" @click="showSettingsPanel = !showSettingsPanel"></div>
  <!-- 推荐按钮 -->
  <el-button type="primary" style="margin-left: 16px" @click="drawer = true" class="recommend-button">
    open
  </el-button>
  <el-drawer v-model="drawer" title="I am the title" :with-header="false">
    <span>站内推荐</span>
    <recommend></recommend>
  </el-drawer>
</template>
<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { storage, checkUserLogin } from '../utils/index'
import { watch } from 'vue';
import { getDefaultEnginesFromServer, getTip, getUserEnginesFromServer } from '../api/get';
import Tag from '../components/Tag.vue';
import Setting from '../components/Setting.vue'
import { engineSwitch } from '../store';
import { updatasaveSearch, deletesaveSearch } from '../api/post'
import { getsaveSearch } from '../api/get'
import HistoryToday from '../components/HistoryToday.vue';
import recommend from '../components/recommend.vue';
const drawer = ref()

const showSettingsPanel = ref(false)
const engines = ref()
const engine_names = ref([])   // 这个是引擎名称 从engines中拿的list
const search_engine = ref("")
const keyword = ref("")
const keywords = ref()
const search_hot_display = ref()
const key_selected = ref(-1)
const engine_siwtch = engineSwitch() // 控制自定义引擎
let isLoggedIn = ref(false)
const showSearchHistory = ref()
const searchRecords = ref()
import {
  Delete,
} from '@element-plus/icons-vue'

// 初始化引擎：
// 准备工作：获得登录状态，将所有的引擎数据拿出来，
// 判断用户是否登录
//    登录，则获得用户数据
//    未登录，使用默认引擎数据
async function initializeEngines() {
  isLoggedIn.value = await checkUserLogin()
  engines.value = await getDefaultEnginesFromServer()
  engine_names.value = engines.value.list
  set_search_engine(engine_names.value[0])

  if (isLoggedIn.value) {
    try {
      await getUserEnginesFromServer().then(res => {
        console.log(res)
        engine_siwtch.switchList = res
      })

    } catch (error) {
      console.error(error)
    }
  } else {
    const localData = storage.get("engines")
    if (localData) {
      engines.value = localData
      engine_names.value = localData.list // 将其移到这里
      set_search_engine(engine_names.value[0])
    } else {
      try {
        const data = await getDefaultEnginesFromServer()
        engines.value = data
        saveToLocal(data)
        engine_names.value = data.list // 将其移到这里
        set_search_engine(engine_names.value[0])
      } catch (error) {
        console.error(error)
      }
    }
  }
}


// bug记录：这里出现过一次问题，组件挂载时候需要engine_names参数的初始值，但是初始化又是异步的，导致搜索框和引擎栏不能显示。
// bug位置：           <span v-for="engine_name in engine_names" v-bind:key="engine_name"
// 初始解决方式：暂时将一些与组件强相关的参数的初始化过程放到了异步方法中，也就是页面组件搜索框和引擎栏的挂载在异步之后
// 可能会出现的问题：经过我的推理，额，不知道，但是感觉会有影响，至少从网页加载时间上（空白页->有内容）变慢

onMounted(() => {
  initializeEngines()
})


function get_search_engine() {
  return storage.get("search_engine")
}
function set_search_engine(engine: any) {
  storage.set("search_engine", engine)
  search_engine.value = engine
}
function saveToLocal(engines: any) {
  storage.set("engines", engines)
}
// 动态更改智能提示，配合watch函数
function get_hot_keywords() {
  if (keyword.value !== '') {
    getTip(search_engine.value, keyword.value).then((res) => {
      keywords.value = res
    })
  } else {
    keywords.value = []
  }
}
// 监听输入内容keyword。
// 如果变化了，就调用get_hot_keywords()方法，更新keywords.value的值
watch(keyword, () => {
  if (key_selected.value == -1) {
    return get_hot_keywords()
  }
})
const result = ref(false)

// 搜索框聚焦：
// 将搜索提示框打开
async function focus() {
  if (isLoggedIn.value) {
    hasSearchHistory()
    if (keyword.value === '' && result.value == true) {
      showSearchHistory.value = true
    }
  }
  search_hot_display.value = "display: block"
  key_selected.value = -1

}

//保存搜索记录
async function saveSearch(this: any) {
  const res = updatasaveSearch(keyword.value);
  res.then(res => {
    console.log(res);
    window.location.reload();
  })
}

async function hasSearchHistory() {
  // 返回true或false，表示是否有搜索历史
  getsaveSearch().then(res => {
    searchRecords.value = res
    console.log(searchRecords.value);

    if (searchRecords.value == '') {
      result.value = false
      return result;
    } else {
      return result.value = true

    }
  })
}

function clearHistory() {
  deletesaveSearch().then(res => {
    console.log(res);
    window.location.reload();
  })
}
// bug记录:因为当blur()函数被调用时，会将搜索提示框关闭，并且触发输入框的失焦事件。
//         由于blur()函数是在点击li标签时调用的，它会导致失焦事件的发生，从而阻止了li@click事件的触发。
// 解决方法：给blur()方法一个延迟操作，这样就可以先执行click事件，再执行blur()函数

// 移出搜索框聚焦状态：
// 将提示框关闭
function blur() {
  setTimeout(() => {
    search_hot_display.value = "display: none";
    showSearchHistory.value = false
    key_selected.value = -1;
  }, 200);
}
// 键盘下键事件
function down() {
  key_selected.value = (key_selected.value + 1) % keywords.value.length
  keyword.value = keywords.value[key_selected.value]
}
// 键盘上建事件
function up() {
  key_selected.value = (key_selected.value - 1) % keywords.value.length
  keyword.value = keywords.value[key_selected.value]
}

function go_history(key:any){
  keyword.value = key
  setTimeout(()=>{
    go_submit(keyword.value)
  },500)
}

function go_submit(key: any) {
  keyword.value = key
  // 获取form标签并执行submit操作,不用管这个submit报错 $refs 和ref不能用 只能这样了,js语法
  const form = document.getElementById('search-form');
  if (form) {
    form.submit();
  }
}

</script>
<style>
@import "../style/search.css";

#setting-icon {
  position: fixed;
  bottom: 20px;
  left: 20px;
  z-index: 2;
  cursor: pointer;
  transition: transform 0.3s ease-in-out;
  /* 定义过渡效果，可以根据需要调整过渡时间和缓动函数 */
}

#setting-icon img {
  width: 24px;
  height: 24px;
}

#setting-icon:hover {
  transform: scale(1.2);
  /* 定义鼠标悬停时的放大效果，可以根据需要调整放大倍数 */
}

#setting-open {
  display: flex;
  flex-direction: row;
  position: fixed;
  bottom: 20px;
  left: 20px;
  z-index: 100003;
  width: 600px;
  height: 400px;
  border: 1px solid black;
  background-color: #ffffff;
  border-radius: 10px;
}


#setting-open>Setting {
  position: absolute;
  top: 0;
  left: 0;
}

.overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 100002;
}

#search-history {
  position: relative;
  width: 300px;
  position: absolute;
  top: 100%;
  left: 0;
  z-index: 10;
  background-color: #fff;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
  padding: 0;
  margin: 0;
  list-style-type: none;
  border-radius: 4px;
  overflow: hidden;
}

#search-history li {
  padding: 6px 12px;
  cursor: pointer;
}

#search-history li:hover {
  background-color: #f2f2f2;
}

.history-today {
  position: fixed;
  /* 或者使用 position: absolute; */
  top: 80px;
  /* 距离顶部的距离 */
  left: 0;
  /* 将组件定位在屏幕的右侧 */
  z-index: 100;
  /* 设置较高的 z-index 值 */
}

.recommend-button {
  position: fixed;
  bottom: 20px;
  right: 20px;
  width: 100px;
  height: 40px;
  background-color: #4CAF50;
  color: white;
  font-size: 16px;
  border-radius: 5px;
  text-align: center;
  line-height: 40px;
  cursor: pointer;
}

.recommend-button:hover {
  background-color: #3e8e41;
}</style>